import { defineStore } from "pinia";
import { getAuthCache, setAuthCache, TOKEN_KEY, USER_INFO_KEY } from "../../utils/auth";
import { getInfo } from "../../api/auth/index"
import { store } from "../index"

export const useUserStore = defineStore({
  id: "user-store",
  state: () => ({
    appId: import.meta.env.VITE_APP_ID,
    authCode: null,
    userInfo: null,
    token: undefined,
    lastUpdateTime: 0,
  }),
  getters: {
    getUserInfo() {
      //console.log(this.userInfo, getAuthCache(USER_INFO_KEY));
      return this.userInfo || getAuthCache(USER_INFO_KEY)
    },
    getToken() {
      return this.token || getAuthCache(TOKEN_KEY)
    },
    getLastUpdateTime() {
      return this.lastUpdateTime;
    },
    async getAuthCode() {
      console.info('🚀 ~ log:getAuthCode方法 ----->', this.authCode);
      if (this.authCode) return this.authCode;
      // return await this.getAuthoizationCode();
    }
  },
  actions: {
    setToken() {
      this.token = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjQ0NDBlYTYzLTBlMzktNDBiMy1hNjkyLTg0NWYzMmRhOTZlYiJ9.RkhYpvdWihzaL214A3WXnDK8marxtPZ4SGeymGhdLLebBHxycpcCBXbCiCeVGUykjGZqUEjWA_NHmgIi8YTONQ';
      // this.token = token ? token : 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjQ0NDBlYTYzLTBlMzktNDBiMy1hNjkyLTg0NWYzMmRhOTZlYiJ9.RkhYpvdWihzaL214A3WXnDK8marxtPZ4SGeymGhdLLebBHxycpcCBXbCiCeVGUykjGZqUEjWA_NHmgIi8YTONQ';
      setAuthCache(TOKEN_KEY, this.token);
    },
    setUserInfo(info) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(USER_INFO_KEY, info);
    },
    // async getUserInfoAction() {
    //   const res = await getInfo();
    //   const userInfo = res.data.user;
    //   userInfo.orgType = res.data.orgType
    //   console.log(userInfo, 1222)
    //   this.setUserInfo(userInfo);
    //   return userInfo
    // },
    // async getAuthoizationCode() {
    //   const appId = this.appId;
    //   console.info('🚀 ~ log:getAuthoizationCode方法 ----->', window.fz);
     
    //   if (window.fz && appId) {
    //     return new Promise((resolve, reject) => {
    //       const params = new URLSearchParams(window.location.search);
    //       const code = params.get("code");
    //       console.info('🚀 ~ log:code ----->', code);
    //       if (code) {
    //         this.authCode = code;
    //         resolve(this.authCode);
    //       } else {
    //         fz.util.getAuthoizationCode({
    //           appId: appId,
    //           onSuccess: async (res) => {
    //             this.authCode = res?.code;
    //             resolve(this.authCode);
    //           },
    //           onFail: (err) => {
    //             resolve(false);
    //           }
    //         })
    //       }
    //     });
    //   } else {
    //     return false;
    //   }
    //   // return this.authCode;  //本地测试使用
    // }

  }
})

export function useUserStoreWithOut() {
  return useUserStore(store);
}